package com.google.gwt.livinglife.server;


import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.livinglife.client.LoginInfo;
import com.google.gwt.livinglife.client.LoginService;
import com.google.gwt.livinglife.client.data.LivingLifeUserData;
import com.google.gwt.livinglife.server.data.LivingLifeUser;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class LoginServiceImpl extends RemoteServiceServlet implements
    LoginService {
	private static final Logger log = Logger.getLogger(LoginServiceImpl.class.getName());
	
  public LoginInfo login(String requestUri) {
    UserService userService = UserServiceFactory.getUserService();
     
    User user = userService.getCurrentUser();
    LoginInfo loginInfo = new LoginInfo();

    if (user != null) {
      loginInfo.setLoggedIn(true);
      loginInfo.setEmailAddress(user.getEmail());
      loginInfo.setNickname(user.getNickname());
      loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
      // Lets see if we have any User Data for this user
      PersistenceManager pm = PMF.get().getPersistenceManager();
      LivingLifeUser living_life_user = null;
      try {
      	living_life_user = pm.getObjectById(LivingLifeUser.class, user.getUserId());
      } catch(Exception e) {
      	living_life_user = new LivingLifeUser(user);
        pm.makePersistent(living_life_user);
      }
      LivingLifeUserData u = DataObjectConverter.getLivingLifeUserData(living_life_user);
      loginInfo.setUser_data(u);
    } else {
      loginInfo.setLoggedIn(false);
      loginInfo.setLoginUrl(userService.createLoginURL(requestUri));
    }
    log.info(loginInfo.toString());
    return loginInfo;
  }
}